package com.zzl.web;

import com.alibaba.fastjson.JSONObject;
import com.zzl.entity.Grade;
import com.zzl.services.GradeServices;
import com.zzl.services.impl.GradeServicesImpl;
import com.zzl.util.DbUtil;
import com.zzl.util.ResponseTypeUtil;
import com.zzl.util.StringEmptyUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

public class GradeSaveListServlet extends HttpServlet {
    DbUtil dbUtil=new DbUtil();
    GradeServices gradeServices=new GradeServicesImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String gradeName=req.getParameter("gradeName");
        String gradeDesc=req.getParameter("gradeDesc");
        String id=req.getParameter("id");
        Grade grade=new Grade();
        grade.setGradeName(gradeName);
        grade.setGradeDesc(gradeDesc);
        if(StringEmptyUtil.isNotEmpty(id)){
            grade.setId(Integer.parseInt(id));
        }
        Connection con=null;
        try {
            con=dbUtil.getCon();
            int saveNums=0;
            JSONObject result=new JSONObject();
            if (StringEmptyUtil.isNotEmpty(id)){
                saveNums=gradeServices.gradeModify(con,grade);
            }else {
                saveNums=gradeServices.gradeAdd(con,grade);
            }
            if(saveNums>0){
                result.put("success","true");
            }else {
                result.put("success","true");
                result.put("errorMsg","保存失败");
            }
            ResponseTypeUtil.write(resp,result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
